﻿using System;
using System.Collections.Generic;

namespace DatabaseStuff.Basic
{
    /// <summary>
    /// Basic implementation of a database table
    /// </summary>
    public class Table: DatabaseStuff.IDBTable
    {
        private class RecordSet : HashMap<object, Record>
        {
            private IDBTable owner;

            public RecordSet(IDBTable _owner)
                : base()
            {
                owner = _owner;
            }

            internal RecordSet(IDictionary<object, Record> _records, IDBTable _owner)
                : base(_records)
            {
                owner = _owner;
            }

            protected override object GetKeyFromValue(Record value)
            {
                return value[owner.Schema.PrimaryKeyField].Data;
            }
        }

        private string name;
        private Schema schema;
        private RecordSet records;

        public Table(string _name, Schema _schema)
        {
            name = _name;
            schema = _schema;
            records = new RecordSet(this);
        }

        /// <summary>
        /// DI-Compatible Constructor
        /// </summary>
        /// <param name="_dict"></param>
        /// <param name="_name"></param>
        /// <param name="_schema"></param>
        internal Table(IDictionary<object, Record> _dict, string _name, Schema _schema)
        {
            name = _name;
            schema = _schema;
            records = new RecordSet(_dict, this);
        }

        public Record GetRecord(object primaryKeyValue)
        {
            if (records.ContainsKey(primaryKeyValue))
                return records[primaryKeyValue];
            else
                throw new ArgumentException("No record could be located using the given primary key: " + primaryKeyValue.ToString());
        }

        public string Name
        {
            get { return name; }
        }

        public Schema Schema
        {
            get { return schema; }
        }

        public ICollection<Record> Records
        {
            get { return records; }
        }

        IDBRecord DatabaseStuff.IDBTable.GetRecord(object primaryKeyValue)
        {
            return GetRecord(primaryKeyValue);
        }

        IDBSchema DatabaseStuff.IDBTable.Schema
        {
            get { return schema; }
        }

        IEnumerable<IDBRecord> DatabaseStuff.IDBTable.Records
        {
            get
            {
                return (IEnumerable<IDBRecord>)Records;
            }
        }

    }
}
